<template>
	<div class="dingtalk-form">
		<transition name="fade-transform" mode="out-in">
			<h3 class="head" :key="isNext">
				{{ isNext ? "请选择你的组织" : "钉钉扫码登录" }}
			</h3>
		</transition>
		<div v-loading="loading" v-if="ddInfo.appid">
			<transition-group name="fade-transform" mode="out-in">
				<div id="dingtalk-box" ref="dingtalkBox" key="dingtalk-box" v-if="!isNext">
					<dd-login :key="loading" :width="340" :height="320" :options="ddOptions" />
				</div>
				<div class="select-biz" key="select-biz" v-if="isNext">
					<div class="ptb-2 tips">你可以选择以下组织</div>
					<ul class="mb-3 biz-list">
						<li
							v-for="(item, index) in groupList"
							:key="index"
							class="pa-1 flex flex-align-center"
							@click="clickGroupItem(item)"
						>
							<cl-avatar
								:src="item.avatar || defaultAvatar"
								shape="square"
								size="medium"
							/>
							<cl-flex1 class="ellipsis plr-2">{{ item.name }}</cl-flex1>
							<i class="arrow el-icon-arrow-right" />
						</li>
					</ul>
				</div>
			</transition-group>
		</div>
		<div v-else class="nosetting">
			未配置钉钉登录参数
		</div>
		<transition name="fade-transform" mode="out-in">
			<div class="opts flex flex-justify-center" :key="isNext">
				<!-- <span @click="switchLogin">账号密码登录</span> -->
				<span type="text" v-if="isNext" @click="toPrev">返回上一级</span>
			</div>
		</transition>
	</div>
</template>
<script>
import { on, off, once, uniqBy } from "@/utils";
import defaultAvatar from "@/assets/logo/logo.png";
import qs from "qs";
import { validate } from "@/utils/validate";
import DdLogin from "./dd-login";
import { mapGetters } from "vuex";
import * as dd from "dingtalk-jsapi";
/**
 * 钉钉扫码登录第三方网站文档
 * https://developers.dingtalk.com/document/app/scan-qr-code-to-login-3rdapp
 */
export default {
	inject: ["login"],
	components: {
		DdLogin
	},
	data() {
		return {
			defaultAvatar,
			isNext: false,
			loading: false,
			groupList: [],
			mobile: "",
			href: "",
			ddInfo: {
				appid: ""
			}
		};
	},
	computed: {
		...mapGetters(["browser"]),
		redirect_uri() {
			const { biz_id } = this.$route.query;

			// let redirect_uri = encodeURIComponent(location.origin + "/login");
			return encodeURIComponent(`${location.origin}/login?biz_id=${biz_id || 0}&redirect=1`);
		},
		ddOptions() {
			return {
				goto: `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.ddInfo.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.redirect_uri}`.replace(
					validate.allspace,
					""
				),
				style: "border:none;background-color:#fff;"
			};
		}
	},
	async created() {
		this.initDingJs();
		this.getDDInfo();
		console.log(this.$route.query);
		const { code, state, redirect } = this.$route.query;
		let isNext = code && state;
		let notInDingTalk = dd.env.platform == "notInDingTalk";
		// if (redirect && isNext) {
		// 	this.$message.warning("扫码登录失败，请刷新重试或选择其他登录方式");
		// }
		if (!isNext) {
			if (!notInDingTalk) {
				let href = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.ddInfo.appid}&response_type=code&scope=snsapi_auth&state=STATE&redirect_uri=${this.redirect_uri}`;
				// alert(href);
				// window.location.href = href;
				this.redirectIframe(href);
			}
			return;
		}
		if (!notInDingTalk) {
			this.dingScanLogin(code);
			return;
		}
		if (window.parent != window) {
			window.parent.dingScanLogin(code);
		}
	},
	mounted() {
		// this.initDDLogin();
		on(window, "message", this.dingtalkMessageEvent);
		this.$once("hook:beforeDestroy", () => {
			off(window, "message", this.dingtalkMessageEvent);
		});
	},

	methods: {
		initDingJs() {
			!(function(window, document) {
				function d(a) {
					var e,
						c = document.createElement("iframe"),
						d = "https://login.dingtalk.com/login/qrcode.htm?goto=" + a.goto;
					(d += a.style ? "&style=" + encodeURIComponent(a.style) : ""),
						(d += a.href ? "&href=" + a.href : ""),
						(c.src = d),
						(c.frameBorder = "0"),
						(c.allowTransparency = "true"),
						(c.scrolling = "no"),
						(c.width = a.width ? a.width + "px" : "365px"),
						(c.height = a.height ? a.height + "px" : "400px"),
						(e = document.getElementById(a.id)),
						(e.innerHTML = ""),
						e.appendChild(c);
				}

				window.DDLogin = d;
			})(window, document);
		},
		// 获取钉钉登录参数
		async getDDInfo() {
			const { biz_id } = this.$route.query;
			if (!biz_id || biz_id == 0) return;
			const data = await this.$service.dinglogin.otherinfo({ biz_id });
			this.ddInfo = data || {};
			if (data.biz_name) {
				// document.title = data.biz_name;
			}
		},
		switchLogin() {
			this.login.isDingtalk = false;
		},
		// 返回上一步
		toPrev() {
			this.isNext = false;
			// setTimeout(() => {
			// 	this.initDDLogin();
			// }, 800);
		},
		//钉钉消息监听
		async dingtalkMessageEvent(event) {
			let origin = event.origin;
			//判断是否来自ddLogin扫码事件。
			if (origin == "https://login.dingtalk.com") {
				// console.log("origin", event.origin);
				console.log("event", event);
				let code = event.data;
				//拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了
				// console.log("loginTmpCode -> " + code);
				let href = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${this.ddInfo.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${this.redirect_uri}&loginTmpCode=${code}`;
				// this.href = href;
				this.redirectIframe(href);
				// alert(href);
				// window.location.href = href;
			}
		},
		redirectIframe(href) {
			// 下面这段代码解决location.href跳转问题
			this.loading = true;
			let iframe = document.createElement("iframe");
			iframe.src = href;
			iframe.style.display = "none";
			window.dingScanLogin = this.dingScanLogin;
			once(iframe, "load", () => {
				document.body.removeChild(iframe);
				this.loading = false;
			});
			document.body.appendChild(iframe);
		},
		async dingScanLogin(code) {
			if (!code) {
				this.$message.warning("扫码登录失败，请刷新重试或选择其他登录方式");
				return;
			}
			console.log("code -> ", code);
			this.loading = true;
			const { biz_id } = this.$route.query;
			const { mobile } = await this.$service.dinglogin.info({ code, biz_id }).catch(e => {
				this.loading = false;
				console.log(e);
				throw e;
			});
			this.mobile = mobile;
			this.getGroupList(mobile);
		},
		async getGroupList(mobile) {
			const res = await this.$store.dispatch("common/getGroupList", { mobile }).done(() => {
				this.loading = false;
			});
			let list = uniqBy(res, "user_id");
			this.groupList = list;
			if (list.length == 1) {
				this.clickGroupItem(list[0]);
				return;
			}
			this.isNext = true;
		},
		async clickGroupItem(item) {
			this.loading = true;
			let form = {
				mobile: this.mobile,
				user_id: item.user_id,
				type: "ding"
				// password: "aabb6688"
			};
			form.signature = btoa(qs.stringify(form));
			// 登录;
			await this.$store.dispatch("selectUserLogin", form).done(() => {
				this.loading = false;
			});
			// 用户信息;
			// await this.$store.dispatch("userInfo");
			// 权限菜单;
			this.$router.push("/");
		}
	}
};
</script>
<style lang="scss">
.login_qrcode_text {
	margin-top: 20px;
	text-align: center;
	color: #898d90;
	font-size: 14px;
}
</style>
<style lang="scss" scoped>
.dingtalk-form {
	box-sizing: border-box;
	padding: 8px 30px 50px;
	text-align: left;
	.head {
		font-size: 20px;
		font-weight: normal;
		height: 62px;
		line-height: 62px;
		border-bottom: 1px solid #ebebeb;
	}
	#dingtalk-box {
		height: 320px;
	}
	.nosetting {
		text-align: center;
		color: #999;
		height: 220px;
		line-height: 220px;
		user-select: none;
	}
	.tips {
		font-size: 12px;
		color: #999;
	}
	.biz-list {
		list-style: none;
		max-height: 300px;
		overflow: auto;
		li {
			height: 60px;
			background: #f0f0f0;
			border-radius: 6px;
			box-sizing: border-box;
			cursor: pointer;
			.arrow {
				color: #999;
			}
		}
		li + li {
			margin-top: 10px;
		}
	}
	.opts {
		span {
			color: #999;
			font-size: 14px;
			line-height: 14px;
			margin: 0 10px;
			cursor: pointer;
			position: relative;
			& + span::before {
				content: "";
				display: block;
				width: 1px;
				height: 10px;
				background: #999;
				position: absolute;
				top: 2px;
				left: -10px;
			}
		}
	}
}
</style>
